<?php
namespace  app\models;

use Yii;
use yii\filters\auth\AuthMethod;
use yii\helpers\Json;

/**
 * Api授权认证类
 *
 * @author myron.mao
 * @version 0.0.1
 * @copyright utrip-easy.com
 */
class ApiAuth extends AuthMethod implements \yii\web\IdentityInterface
{

    public $authid;
    public $app_code;
    public $app_secret;
    public $auth_key;
    public $access_token;
    public $token_utc;
    public $allowance;
    public $allowance_updated_at;


    public $signParam = 'sign';
    public $timeParam = 'ut';
    private $ignoreParams = ['r'];  // yii2框架自带路径参数，忽略
    private $private_key = '12345678';

    const TIME_LOSE = '600';

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        $auth = SysAuth::getAuthById($id);
        if( null == $auth ) return null;
        return new static($auth);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $auth = SysAuth::getAuthByToken($token);
        if( null == $auth ) return null;
        $utc = gmdate('U');
        if($utc > $auth->token_utc){
            return null;
        }
        return new static($auth);
    }


    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->authid;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }

    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $sign = $request->get($this->signParam);
        $utc = $request->get($this->timeParam);

        if (is_string($sign)) {
            if (!$this->checkSign($sign, $utc)) {
                $this->handleFailure($response);
            }
            return true;
        }

        if ($sign !== null) {
            $this->handleFailure($response);
        }
        return null;
    }

    private function checkSign($sign, $utc)
    {
        if( (gmdate('U')-$utc) > self::TIME_LOSE ) {
            return false;
        }
        return $this->getSign() === $sign;

    }

    public function getSign($arr_get_params=[])
    {
        if(empty($arr_get_params)) {
            $params = $this->getGetParams();
        }else {
            $params = $arr_get_params;
        }

        $key = implode(',', $params);
        $raw = Yii::$app->request->getRawBody();
        return md5($this->private_key . md5($key) . md5($raw) ) ;
    }

    public function getGetParams()
    {
        $getParams = Yii::$app->request->get();

        unset($getParams[$this->signParam]);
        foreach($this->ignoreParams as $param)
        {
            unset($getParams[$param]);
        }
        ksort($getParams);
        return $getParams;
    }

    public function getRaw()
    {
        $raw = Yii::$app->request->getRawBody();
        return Json::decode($raw);
    }

}